﻿#pragma once
#include "Common.h"

template <class T>
class ObjectPool
{
	char* _memory = nullptr; //指向内存块的指针
	void* _freeList = nullptr; //管理回收的内存对象的自由链表
	size_t _remainMemNum = 0; //内存块剩余内存字节数

public:
	T* New()
	{
		T* object = nullptr;
		if (_freeList)//如果自由链表有对象，直接取一个
		{
			void* next = *(void**)_freeList;
			object = (T*)_freeList;
			_freeList = next;
		}
		else
		{
			if (_remainMemNum < sizeof(T))
			{
				_remainMemNum = 16 * 1 << PAGE_SHFT;//16 * 8k = 128k
				//char* tmp = (char*)malloc(_remainMemNum);
				char* tmp = (char*)SystemAlloc(_remainMemNum >> PAGE_SHFT);
				if (tmp == nullptr)
				{
					throw std::bad_alloc(); //抛异常
				}
				_memory = tmp;
			}
			object = (T*)_memory;
			size_t sz = sizeof(T);
			sz = sz > sizeof(void*) ? sz : sizeof(void*);
			_remainMemNum -= sz;
			_memory += sz;
		}
		//使⽤定位new调⽤T的构造函数初始化
		new(object)T;
		return object;
	}
	void Delete(T* object)
	{
		// 显⽰调⽤的T的析构函数进⾏清理 
		object->~T();

		*(void**)object = _freeList;
		_freeList = object;//void*（空指针）可以接收、持有任何类型的指针
	}
};

class TreeNode
{
	int _val;
	TreeNode* _left;
	TreeNode* _right;
public:
	TreeNode(int val = int(), TreeNode* left = nullptr, TreeNode* right = nullptr)
		:_val(val)
		, _left(left)
		, _right(right)
	{

	}
};

